import {ConfigProvider,Button,Tag,Table, Col, Popconfirm, message,Modal,Form,Input, DatePicker} from "antd";
import zhCN from 'antd/locale/zh_CN'
import {ExclamationCircleOutlined} from '@ant-design/icons'
import './App.css'
import { useEffect, useState } from "react";
import taskService from './service/task'
const {Column}=Table
const TASK_STATUS=[
	{label:'全部',value:'all'},
	{label:'未完成',value:1},
	{label:'已完成',value:2}
]

function App() {

	const [filter,setFilter]=useState('all');
	const [tasks,setTasks]=useState([])
	const [filteredTasks,setFilteredTasks]=useState([])
	const [loading,setLoading]=useState(false)
	const [addTaskVisible,setAddTaskVisible]=useState(false)
	const [form]=Form.useForm();
	const retrieveTasks=async ()=>{
		try {
			setLoading(true)
			let tasks=await taskService.getTasks()
			console.log(tasks);
			setTasks(tasks)
			//message.success('获取数据成功')
		} catch (error) {
			message.error('获取数据失败')
		}finally{
			setLoading(false)
		}
	}
	const handleDelete=async (id)=>{
		try {
			await taskService.deleteTask(id)
			await retrieveTasks();
			message.success('任务删除成功')
		} catch (error) {
			message.error('任务删除失败')
		}
	}
	const handleComplete=async (id)=>{
		try {
			await taskService.completeTask(id)
			await retrieveTasks();
			message.success('任务完成成功')
		} catch (error) {
			message.error('任务完成失败')
		}
	}
	const handleNewTask=async ()=>{
		try {
			let values=await form.validateFields();
			console.log(values.expected_completion_time);
			await taskService.createTask({
				...values,
				expected_completion_time:values.expected_completion_time.format('YYYY-MM-DD HH:mm:ss')
			})
			console.log(values);
			setAddTaskVisible(false)
			retrieveTasks()
			form.resetFields()
			message.success('任务创建成功')
		} catch (error) {
			// //获取错误字段
			// const {errorFields} = error;
			// //声明错误消息数组
			// let errorMessages = [];
			// //遍历错误字段
			// errorFields.forEach(errorField=>{
			// 	//把每个错误字段的错误技术添加到错误消息数组
			// 	errorMessages.push(...errorField.errors);
			// });
			// //message.error(errorMessages.join(','));
			console.error(error)
		}
	}
	useEffect(()=>{
		retrieveTasks();
	},[])
	useEffect(()=>{
		//当tasks或filter的值发生变化后，会重新执行副作用函数
		//对原始的数组进行过滤，如果当前的过滤器是all或者
		let filteredTasks=tasks.filter(task=>filter==='all'||task.status==filter)
		console.log(filteredTasks);
		setFilteredTasks(filteredTasks);
	},[tasks,filter])
	return (
		<ConfigProvider locale={zhCN}>
			<div className="todos">
				<div className="todos-header">
					<h3>TASK OA管理系统</h3>
					<Button type="primary" onClick={()=>setAddTaskVisible(true)}>新增任务</Button>
				</div>
				<div className="todos-tags">
					{
						TASK_STATUS.map(({label,value})=>(
							<Tag key={value} 
							   color={filter === value?'orange':'default'} 
							   onClick={()=>setFilter(value)}>
								{label}
							</Tag>
						))
					}
				</div>

				<Table dataSource={filteredTasks} rowKey='id' loading={loading}>
					<Column title="编号" dataIndex='id' />
					<Column title="任务描述" dataIndex='description' />
					<Column title="状态" dataIndex='status' render={
						(value)=>value===1?'未完成':'已完成'
					}/>
					<Column title="预计完成时间" dataIndex='expected_completion_time' />
					<Column title="实际完成时间" dataIndex='actual_completion_time' />
					<Column title="操作" dataIndex='id' render={
						(_,record)=>{
							return (
								<>
									<Popconfirm 
									onConfirm={()=>handleDelete(record.id)}
									title="确定要删除吗？" 
									icon={<ExclamationCircleOutlined 
									style={{color:'red'}} 
									/>}>
										<a>删除</a>
									</Popconfirm>
									<Popconfirm 
									onConfirm={()=>handleComplete(record.id)}
									title="确定完成了吗？" 
									icon={<ExclamationCircleOutlined 
									style={{color:'green'}} />}>
										<a style={{marginLeft:'10px'}}>完成</a>
									</Popconfirm>
								</>
							)
						}
					} />
					
				</Table>
			</div>
			<Modal title="新增任务" 
				open={addTaskVisible} 
				onCancel={()=>{setAddTaskVisible(false)}}
				onOk={handleNewTask}
				>
					<Form form={form} layout="vertical">
						<Form.Item 
						label="任务描述"
						name="description"
						rules={[{required:true,message:'请输入任务描述'}]}
						>
							<Input.TextArea rows={4}></Input.TextArea>
						</Form.Item>
						<Form.Item
						label="预计完成时间"
						name="expected_completion_time"
						rules={[{required:true,message:'请输入预计完成时间'}]}
						>
							<DatePicker showTime placement="topRight"/>
						</Form.Item>
					</Form>

			</Modal>

		</ConfigProvider>
	);
}

export default App;
